package ahjava.io;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;
public class NIO02FileCopy {
	static int BUFF_LEN = 1024 * 1024;// 缓冲区越大，NIO效率越明显
	public static void main(String[] args) throws IOException {
		String source = "D:\\insanity06 Cardio Abs 有氧腹肌 中文.mp4";
		System.out.println(new File(source).length() / 1024 / 1024 + "MB");
		String destination = "D:\\nio.mp4";
		long start = 0;
		long end = 0;
		start = System.currentTimeMillis();
		nioCopy(source, destination);
		end = System.currentTimeMillis();
		System.out.println("NIO copy:" + (end - start));
		destination = "D:\\io.mp4";
		start = System.currentTimeMillis();
		ioCopy(source, destination);
		end = System.currentTimeMillis();
		System.out.println("IO copy:" + (end - start));
	}
	static void nioCopy(String source, String destination) throws IOException {
		FileInputStream fis = new FileInputStream(source);
		FileOutputStream fos = new FileOutputStream(destination);
		FileChannel ic = fis.getChannel();
		FileChannel oc = fos.getChannel();
		ByteBuffer bb = ByteBuffer.allocate(BUFF_LEN);
		while (true) {
			bb.clear();
			int len = ic.read(bb);
			if (len == -1) {
				break;
			}
			bb.flip();
			oc.write(bb);
		}
		ic.close();
		oc.close();
		fis.close();
		fos.close();
	}
	static void ioCopy(String source, String destination) throws IOException {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		fis = new FileInputStream(source);
		fos = new FileOutputStream(destination);
		// 创建字节数组，作为临时缓冲
		byte[] buf = new byte[BUFF_LEN];
		int len = -1;
		// 循环从文件输入流中读取数据
		while ((len = fis.read(buf)) != -1) {
			// 写入到文件输出流中
			fos.write(buf, 0, len);
		}
		// 关闭流
		fis.close();
		fos.close();
	}
}
